package storage

import (
	"context"
	"github.com/gin-gonic/gin"
	"github.com/tencentyun/cos-go-sdk-v5"
	"net/http"
	"net/url"
	"path/filepath"
)

var Cos = new(cosStorage)

type cosStorage struct{}

// 本地保存
func (s *cosStorage) Save(c *gin.Context, config *StructConfig) (*StructFile, error) {
	fd, headers, err := c.Request.FormFile("file")
	if err != nil {
		return nil, err
	}
	bucketUrl := "https://" + config.Cos.Bucket + ".cos." + config.Cos.Region + ".myqcloud.com"
	u, _ := url.Parse(bucketUrl)
	b := &cos.BaseURL{BucketURL: u}
	client := cos.NewClient(b, &http.Client{
		Transport: &cos.AuthorizationTransport{
			SecretID:  config.Cos.SecretID,
			SecretKey: config.Cos.SecretKey,
		},
	})
	// 通过文件流上传对象
	_, err = client.Object.Put(context.Background(), config.SavePath+config.SaveName, fd, nil)
	if err != nil {
		return nil, err
	}
	// 文件后缀
	suffix := filepath.Ext(headers.Filename)
	file := StructFile{
		Storage:      "cos",
		OriginalName: headers.Filename,
		Name:         config.SaveName,
		Size:         headers.Size,
		Suffix:       suffix,
		Type:         headers.Header.Get("Content-Type"),
		Path:         config.SavePath + config.SaveName,
		Url:          bucketUrl + "/" + config.SavePath + config.SaveName,
	}
	return &file, nil
}

// 删除文件
func (s *cosStorage) Del(config *StructConfig, objects []string) error {
	bucketUrl := "https://" + config.Cos.Bucket + ".cos." + config.Cos.Region + ".myqcloud.com"
	u, _ := url.Parse(bucketUrl)
	b := &cos.BaseURL{BucketURL: u}
	client := cos.NewClient(b, &http.Client{
		Transport: &cos.AuthorizationTransport{
			SecretID:  config.Cos.SecretID,
			SecretKey: config.Cos.SecretKey,
		},
	})
	obs := []cos.Object{}
	for _, v := range objects {
		obs = append(obs, cos.Object{Key: v})
	}
	opt := &cos.ObjectDeleteMultiOptions{
		Objects: obs,
		// 布尔值，这个值决定了是否启动 Quiet 模式
		// 值为 true 启动 Quiet 模式，值为 false 则启动 Verbose 模式，默认值为 false
		// Quiet: true,
	}
	_, _, err := client.Object.DeleteMulti(context.Background(), opt)
	if err != nil {
		return err
	}
	return nil
}
